/**
 * 
 */
package top.ewind.interceptor.mqtt;

import java.nio.ByteBuffer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.utils.JsonUtils;

import top.ewind.controller.common.RedisConstants;
import top.ewind.model.SysDictory;
import top.ewind.util.DateUtil;


/**
 * @author wangchao
 *
 */
public class DeviceStrategy extends AbstractMsgStrategy implements IMsgStrategy {

	/* (non-Javadoc)
	 * @see top.ewind.interceptor.mqtt.IMsgStrategy#onConnect(java.lang.String)
	 */
	private final static Logger log = LoggerFactory.getLogger(DeviceStrategy.class);

	@Override
	public void onConnect(String id) {
		System.out.println("fd");
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onDisconnect(String id) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPublish(String pid, String id, ByteBuffer buff) {
		System.out.println(pid);
		// TODO Auto-generated method stub
		
	}
	/*public void onConnect(String id) {
		//更新设备状态
		Device device = Device.dao.findById(id);
		if(device!=null){
			device.set("stat", 2).set("starttime", new Date());
			if(device.getWorktime()==null){
				device.setWorktime(new Date());
				Redis.use().hincrBy(RedisConstants.DEVICE_WORK_DAY+device.getPid(), DateUtil.todayStr(), 1);
				Redis.use().hincrBy(RedisConstants.DEVICE_WORK_MONTH+device.getPid(), DateUtil.monthStr(), 1);
			}
			device.update();
			String ucmsg = "{\"deviceid\":\""+id+"\"}";
			try {
				//规则转发
				DeviceForward.forwardRule(device.getPid(),1,1,ucmsg);
			} catch (Exception e) {
				// do nothing
			}
		}
	}

	 (non-Javadoc)
	 * @see top.ewind.interceptor.mqtt.IMsgStrategy#onDisconnect(java.lang.String)
	 
	@Override
	public void onDisconnect(String id) {
		//更新设备状态
		Device device = Device.dao.findById(id);
		if(device!=null&&device.getStat()==2){
			DeviceOnline devon = new DeviceOnline().set("nid", device.getNid()).set("deviceid", device.getId())
					.set("starttime", device.getStarttime()).set("endtime",new Date());
			devon.save();
			device.set("stat", 1).set("starttime", null).update();
			String ucmsg = "{\"deviceid\":\""+id+"\"}";
			try {
				//规则转发
				DeviceForward.forwardRule(device.getPid(),1,0,ucmsg);
			} catch (Exception e) {
				// do nothing
			}
		}

	}

	 (non-Javadoc)
	 * @see top.ewind.interceptor.mqtt.IMsgStrategy#onPublish(java.lang.String, java.nio.ByteBuffer)
	 
	@Override
	public void onPublish(String pid,String id, ByteBuffer buff) {
		String str = decodeToStr(buff);
		log.error("设备消息："+str);
		HashMap<?, ?> map = JsonUtils.parse(str, HashMap.class);
		//设备报警
		@SuppressWarnings("rawtypes")
		Map ostat = Redis.use().hgetAll(RedisConstants.DEVICE_STAT+id);
		//log.debug("上一次记录："+ostat);
		//行车轨迹
		if(map.containsKey("j")&&map.containsKey("w")){
			//log.debug("行车轨迹："+map);
			track(map,id);
		}
		//耗电量变化
		if(map.containsKey("estat")&&map.containsKey("ep")&&map.containsKey("ew")){
			//log.debug("耗电变化："+map);
			battery(map,id);
		}
		//规则转发
		try {
			DeviceForward.forwardRule(pid,0,null,str);
		} catch (Exception e) {
			//do nothing
		}
		//保存状态
		for (Map.Entry<?, ?> entry : map.entrySet()) {
			Redis.use().hset(RedisConstants.DEVICE_STAT+id, entry.getKey(), entry.getValue());
			//log.debug("保存状态："+entry);
        }
	}

	private void track(HashMap<?, ?> map,String id){
		Integer tid = Redis.use().get(RedisConstants.DEVICE_TRACK_ID+id);
		if(tid==null){
			if(map.containsKey("start")&&((Integer)map.get("start"))==1){
				log.error("start:1------"+id);
				DeviceTrack dt = new DeviceTrack().set("mac", id);
				dt.save();
				Redis.use().set(RedisConstants.DEVICE_TRACK_ID+id,dt.getId());
			}
		}
		else{
			if(!map.containsKey("start")&&!map.containsKey("end")){
				HashMap<String,Object> rmap = new HashMap<String,Object>();
				rmap.put("j", map.get("j"));
				rmap.put("w", map.get("w"));
				rmap.put("time",System.currentTimeMillis());
				Redis.use().rpush(RedisConstants.DEVICE_TRACK+tid,rmap);
			}
			else if(map.containsKey("end")){
				log.error("end:1------"+id);
				DeviceTrack dt = DeviceTrack.dao.findById(tid);
				Redis.use().del(RedisConstants.DEVICE_TRACK_ID+id);
				if(dt!=null){
					Date time = new Date();
					dt.set("endtime",time).set("endday",time).set("dmile", map.get("dmile")).set("dmin", map.get("dmin")).set("dspeed", map.get("dspeed"));
					dt.update();
					
					里程数兑换积分
					ShopAmountHis shopamounthis = new ShopAmountHis();
					String point = SysDictory.getConfig("milePoint");
					int int_p = 0;
					try {
					    int_p = Integer.parseInt(point);
					} catch (NumberFormatException e) {
					    e.printStackTrace();
					} 
					String mac = dt.getMac();
					String s = map.get("dmile").toString();
					Double d = Double.parseDouble(s);
					try {
					   int amountmile = (int) (d*int_p);
					   
						DeviceBind userid = DeviceBind.dao.findFirst("select userid from device_bind where btype = 8 and mac='"+mac+"'");
						if(userid!=null){
							shopamounthis.set("userid", userid.getUserid()).set("piont", amountmile)
						    .set("reason", "行驶里程获得"+amountmile+"积分").set("intime", new Date()).set("type",2).save();
							if(amountmile!=0){
								   DeviceUser dvu = DeviceUser.dao.findById(userid.getUserid());
									int amounts = dvu.getAmount()+amountmile;
									new DeviceUser().set("id",dvu.getId()).set("amount", amounts).update();
								}
						}
					} catch (NumberFormatException e) {
					    e.printStackTrace();
					} 
				}
			}
		}
	}
	
	@SuppressWarnings("rawtypes")
	private void battery(HashMap<?, ?> map,String id){
		int estat = (Integer)map.get("estat");
		if(estat==1){
			return;
		}
		Map ostat = Redis.use().hgetAll(RedisConstants.DEVICE_STAT+id);
		if(ostat!=null&&ostat.containsKey("ep")&&ostat.containsKey("ew")){
			int oep = (Integer)ostat.get("ep");
			int oew = (Integer)ostat.get("ew");
			int ep = oep-(Integer)map.get("ep");
			int ew = oew-(Integer)map.get("ew");
			if(ep>0&&ew>0){
				String now = DateUtil.now();
				String today = DateUtil.today();
				HashMap<String,Object> rmap = new HashMap<String,Object>();
				rmap.put("ep", ep);
				rmap.put("ew", ew);
				Redis.use().hincrBy(RedisConstants.STATIS_BATTERY_DAY_PER+id,today,ep);
				Redis.use().hincrBy(RedisConstants.STATIS_BATTERY_DAY+id,today,ew);
				Redis.use().hincrBy(RedisConstants.STATIS_BATTERY_HOUR_PER+id+":"+now.substring(0,8),now.substring(8, 10),ep);
				Redis.use().hincrBy(RedisConstants.STATIS_BATTERY_HOUR+id+":"+now.substring(0,8),now.substring(8, 10),ew);
			}
		}
	}*/
}
